package member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import member.domain.MemberReceiveAddress;
import member.service.MemberReceiveAddressService;
import member.mapper.MemberReceiveAddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author panghu
 * @description 针对表【ums_member_receive_address(会员收货地址)】的数据库操作Service实现
 * @createDate 2023-03-04 21:04:05
 */
@Service
public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressMapper, MemberReceiveAddress>
        implements MemberReceiveAddressService {

    @Override
    public void updateMemberById(MemberReceiveAddress memberReceiveAddress) {
        // 判断用户是否将此收货地址设置为默认收货地址
        changeDefaultStatus(memberReceiveAddress);
        this.updateById(memberReceiveAddress);
    }

    @Override
    public void saveMember(MemberReceiveAddress memberReceiveAddress) {
        changeDefaultStatus(memberReceiveAddress);
        // 新增
        this.save(memberReceiveAddress);
    }

    /**
     * 维护用户的默认收货地址状态
     *
     * @param memberReceiveAddress
     */
    private void changeDefaultStatus(MemberReceiveAddress memberReceiveAddress) {
        // 判断用户是否将此收货地址设置为默认收货地址
        if (memberReceiveAddress.getDefaultStatus() == 1) {
            LambdaQueryWrapper<MemberReceiveAddress> queryWrapper = new LambdaQueryWrapper<MemberReceiveAddress>()
                    .eq(MemberReceiveAddress::getDefaultStatus, 1)
                    .eq(MemberReceiveAddress::getMemberId, memberReceiveAddress.getMemberId());
            // 是，需要将除这个外所有的收货地址的状态设置为0
            if (!ObjectUtils.isEmpty(memberReceiveAddress.getId())) {
                // 修改操作
                queryWrapper.ne(MemberReceiveAddress::getId, memberReceiveAddress.getId());
            }
            MemberReceiveAddress one = this.getOne(queryWrapper);
            if (!ObjectUtils.isEmpty(one)) {
                one.setDefaultStatus(0);
                this.updateById(one);
            }
        }
    }
}




